#include <rtc.h>
beijing_time rtc_time;

//BCD码转十进制函数，输入BCD，返回十进制
u8 BCD_to_int(u8 bcd)
{
	u8 Decimal;
	Decimal = bcd >> 4;
	return (Decimal = Decimal * 10 + (bcd &= 0x0F));
}
//十进制转BCD函数
u8 int_to_BCD(u8 bcd)
{
	return ((bcd / 10) << 4) + (bcd % 10);
}
//读RTC数据
ErrorStatus fnRTCDrive_Read(u8 *Dst)
{
	Dst[0] = BCD_to_int(RTC->SC);
	Dst[1] = BCD_to_int(RTC->MN);
	Dst[2] = BCD_to_int(RTC->HR);
	Dst[4] = BCD_to_int(RTC->DT);
	Dst[5] = BCD_to_int(RTC->MO);
	Dst[6] = BCD_to_int(RTC->YR);
	Dst[3] = RTC->DW + 1;
	return (SUCCESS);
}
//写RTC数据
ErrorStatus fnRTCDrive_Write(u8 *Dst, u8 Repeat)
{
	u8 Buffer[7], i;
	RTC->CTRL |= 0x00000100; //RTC Write enable
	for (; Repeat > 0; Repeat--)
	{
		if (!(RTC->CTRL & 0x200))
			break;
		fnRTCDrive_Delay();
	}
	if (RTC->CTRL & 0x200)
		return (ERROR);
	RTC->DW = Dst[3] - 1;
	fnRTCDrive_Delay();
	RTC->YR = int_to_BCD(Dst[6]);
	fnRTCDrive_Delay();
	RTC->MO = int_to_BCD(Dst[5]);
	fnRTCDrive_Delay();
	RTC->DT = int_to_BCD(Dst[4]);
	fnRTCDrive_Delay();
	RTC->HR = int_to_BCD(Dst[2]);
	fnRTCDrive_Delay();
	RTC->MN = int_to_BCD(Dst[1]);
	fnRTCDrive_Delay();
	RTC->SC = int_to_BCD(Dst[0]);
	fnRTCDrive_Delay();
	if (!fnRTCDrive_Read(Buffer))
		return (ERROR);
	for (i = 6; i > 0; i--)
	{
		if (Buffer[i] != Dst[i])
			return (ERROR);
	}
	RTC->CTRL &= 0xfffffeff; // RTC Write Disable
	return (SUCCESS);
}

//RTC初始化
ErrorStatus fnRTCDrive_Init(void)
{
	u16 AddingTimes = 0;
	RTC->CTRL = 0x100;
	while (RTC->CTRL & 0x200)
	{
		if (++AddingTimes > 65000)
			return (ERROR); //
	}
	RTC->CTRL = 0x100;
	fnRTCDrive_Delay();
	RTC->CTRL = 0x141;
	fnRTCDrive_Delay();
	set_rtc_time(20, 1, 1, 0, 0, 0);
	return (SUCCESS);
}

//读系统时钟
ErrorStatus fnSysClock_Read(beijing_time *Clock)
{
	u8 Buffer[7];
	if (!fnRTCDrive_Read(Buffer))
		return (ERROR);
	Clock->sec = (Buffer[0]) & 0x7f;
	Clock->min = (Buffer[1]) & 0x7f;
	Clock->hour = (Buffer[2]) & 0x3f;
	Clock->date = (Buffer[4]) & 0x3f;
	Clock->month = (Buffer[5]) & 0x1f;
	Clock->year = (Buffer[6]);
	Clock->iWeek = (Buffer[3]) & 0x07;
	return (SUCCESS);
}

ErrorStatus fnSysClock_Write(beijing_time *Clock)
{
	u8 Buffer[7];
	Buffer[0] = (Clock->sec) & 0x7f;
	Buffer[1] = (Clock->min) & 0x7f;
	Buffer[2] = (Clock->hour) & 0x3f;
	Buffer[3] = (Clock->iWeek) & 0x07;
	Buffer[4] = (Clock->date) & 0x3f;
	Buffer[5] = (Clock->month) & 0x1f;
	Buffer[6] = (Clock->year);
	return (fnRTCDrive_Write(Buffer, 3));
}
